<template>
  <CDialog
    title="材料替换"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    size="small"
    @cancel="handleClose"
    @confirm="handleConfirm"
  >
    <div class="low-carbon-material-dialog-container" v-loading="loading">
      <el-form ref="formRef" :rules="rules" :model="formData" label-position="left">
        <el-form-item label="常规材料：" prop="materialName">
          <GSelectV2
            v-model="formData.materialName"
            placeholder="请输入后选择"
            filterable
            clearable
            :options="materialOpts"
          />
        </el-form-item>
        <div class="g-flex-center-center g-mb20 g-font-16n2" style="height: 32px">替换为</div>
        <el-form-item label="低碳材料：" prop="relationNo">
          <GSelect filterable placeholder="请选择" v-model="formData.relationNo" clearable>
            <el-option
              v-for="item in lowCarbonMaterialOpts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </GSelect>
        </el-form-item>
      </el-form>
    </div>
  </CDialog>
</template>
<script lang="ts" setup name="ReplaceLowCarbonMaterialDialog">
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { GSelect, GSelectV2 } from '@/components/GSelect/index';
import { useMessage } from '@/hooks/useMessage';
import {
  getAllLowCarbonMaterialList,
  postReplaceLowCarbonMaterial
} from '@/apis/system/config/lowCarbonMaterial';
import { getMaterialNameList } from '@/apis/pcf/myModel/modelDetail';
import { rules } from './rules';
import { onMounted } from 'vue';

interface ReplaceLowCarbonMaterialDialogProps {
  visible: boolean;
  nodeNo: string;
  modelNo: string;
}
const props = withDefaults(defineProps<ReplaceLowCarbonMaterialDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

watch(
  () => props.visible,
  val => {
    if (val) {
      formData.materialName = undefined;
      formData.relationNo = undefined;
      init();
    }
  }
);
const formRef = ref();
const loading = ref(false);
const formData = reactive({
  materialName: undefined,
  relationNo: undefined
});
// eslint-disable-next-line no-undef
const materialOpts = ref<LabelValueOptions>([]);
// eslint-disable-next-line no-undef
const lowCarbonMaterialOpts = ref<LabelValueOptions>([]);

// NOTE 常规材料需要每次打开都刷新，因为列表操作会影响
async function init() {
  getMaterialNameListFn();
}

// 低碳材料不需要每次都刷新
onMounted(() => {
  getAllLowCarbonMaterialListFn();
});

async function getAllLowCarbonMaterialListFn() {
  try {
    const res = await getAllLowCarbonMaterialList();
    lowCarbonMaterialOpts.value = res.map(item => {
      return {
        label: item.materialName,
        value: item.relationNo
      };
    });
  } catch (error) {
    lowCarbonMaterialOpts.value = [];
  }
}

async function getMaterialNameListFn() {
  try {
    const res = await getMaterialNameList(props.modelNo);
    // for (let i = 0; i < 10000; i++) {
    //   materialOpts.value.push({
    //     label: res[0] + i,
    //     value: res[0] + i
    //   });
    // }
    materialOpts.value = res.map(item => {
      return {
        label: item,
        value: item
      };
    });
  } catch (error) {
    materialOpts.value = [];
  }
}

function handleConfirm() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        await postReplaceLowCarbonMaterial(
          props.nodeNo,
          formData.relationNo,
          formData.materialName
        );
        createMessage.success('保存成功！');
        loading.value = false;
        emits('refresh', props.nodeNo);
        handleClose();
      } catch (error) {
        console.log('error', error);
        loading.value = false;
      }
    }
  });
}

function handleClose() {
  dialogVisible.value = false;
}
</script>
<style lang="scss" scoped>
.low-carbon-material-dialog-container {
  :deep(.el-form--inline .el-form-item) {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style>
